let jwt = require("jsonwebtoken");
let config = require('../config');

const utils = {
    //登录认证
    requireAuth: (req, res, next) => {
        let token = req.body.authorization;
        if(token){
            jwt.verify(token, config.jwtSecret, (err, decoded) => {
                if(err){
                    if(err.name === 'TokenExpiredError'){
                        return res.status(401).json({error: '认证码失效，请重新登录！'});
                    }else{
                        return res.status(401).json({error: '认证失败！'});
                    }
                }else{
                    if(decoded.openId){
                        req.openid = decoded.openId;
                        next();
                    }else{
                        res.status(401).json({error: '认证失败2！'});
                    }
                }
            })
        }else{
            return res.status(401).json({error: '请提供认证码！'});
        }
    },

    // openId加密
    generateToken: (user) => {
        return jwt.sign(user, config.jwtSecret, {
            expiresIn: 7200
        })
    }
}

module.exports = utils;